package com.qfedu.edu.seckill.orderservice.slot.impl;

import com.qfedu.edu.seckill.orderservice.slot.base.SlotChain;
import com.qfedu.edu.seckill.orderservice.slot.generic.GenericSlot;
import com.qfedu.edu.seckill.utils.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

/**
 * @author xiaobobo
 * @title: SlotChainImpl
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:53
 */
@Component
@Slf4j
public class SlotChainImpl implements SlotChain {

    @Autowired
    private List<GenericSlot> genericSlots;

    //申明一个处理容器
    private TreeSet<GenericSlot> genericSlotTreeSet;

    @Autowired
    private RedissonClient redissonClient;

    @PostConstruct
    public void init() {
        genericSlotTreeSet = new TreeSet<>();
        genericSlotTreeSet.addAll(genericSlots);
    }

    @Override
    public void dealRequest(HttpServletRequest request, HttpServletResponse response) {
        //在下面就可以遍历这个集合处理数据了
        //TODO 这个分布式锁 应该加在这里
        //首先获取这个锁
        RLock rLock = redissonClient.getLock("锁");
        try {
            if(rLock.tryLock()){
                Iterator<GenericSlot> iterator = genericSlotTreeSet.iterator();
                while (iterator.hasNext()) {
                    GenericSlot next = iterator.next();
                    next.dealRequest(request,response);
                }
            }
        }catch (Exception err){
            //也要释放锁
            log.info("添加分布式锁失败{}....", ExceptionUtils.getExceptionStackMessage(err));
        }finally {
            //这里要释放锁
            rLock.unlock();
        }

    }

}
